package org.raymond.icloud.modules.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.raymond.icloud.apis.admin.entity.*;
import org.raymond.icloud.apis.admin.entity.enums.SexEnum;
import org.raymond.icloud.apis.admin.vo.UserInfoVO;
import org.raymond.icloud.apis.admin.vo.entity.SysPermissionVO;
import org.raymond.icloud.apis.admin.vo.entity.SysUserVO;
import org.raymond.icloud.common.core.constants.ErrorCode;
import org.raymond.icloud.common.core.exception.BaseException;
import org.raymond.icloud.common.core.mybatis.UserIdContext;
import org.raymond.icloud.common.core.util.RandomValueUtils;
import org.raymond.icloud.modules.admin.mapper.TSysUserMapper;
import org.raymond.icloud.modules.admin.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class TSysUserServiceImpl extends ServiceImpl<TSysUserMapper, TSysUser> implements ITSysUserService {
    @Autowired
    private ITSysOrgService itSysOrgService;
    @Autowired
    private ITSysRoleService itSysRoleService;
    @Autowired
    private ITSysPermissionService itSysPermissionService;

    @Override
    public TSysUser findByUsername(String username) {
        LambdaQueryWrapper<TSysUser> getWrapper = new LambdaQueryWrapper<>();
        getWrapper.eq(TSysUser::getUsername, username);
        TSysUser tSysUser = getOne(getWrapper);
        return tSysUser;
    }

    @Override
    public boolean createRandomUser(int count) {
        if(count<=0) return true;

        List<TSysUser> list = new ArrayList<>();
        for(int i=0; i<=count; i++){
            TSysUser user = buildRandomUser();
            list.add(user);
        }
        saveBatch(list);
        return true;
    }

    @Override
    public UserInfoVO currentUserInfo() {
        Long userId = UserIdContext.getUserId();
        if(userId==null){
            throw new BaseException(ErrorCode.UNAUTHORIZED);
        }
        TSysUser sysUser = getById(userId);

        UserInfoVO vo = new UserInfoVO();
        BeanUtils.copyProperties(sysUser, vo);
        vo.setUserId(userId);
        return vo;
    }

    @Override
    public List<SysPermissionVO> currentUserPermissions() {
        Long userId = UserIdContext.getUserId();
        if(userId==null){
            throw new BaseException(ErrorCode.UNAUTHORIZED);
        }
        List<TSysRole> roleList = itSysRoleService.getsAssociatedRoleByUserId(userId);
        if(CollectionUtils.isEmpty(roleList)) {
            String message = String.format("用户[%s]未配置任何角色", userId);
            throw new BaseException(ErrorCode.NOT_CONFIGURED, message);
        }
        log.debug("用户[{}]配置的角色: {}", userId, roleList.stream().map(TSysRole::getName).collect(Collectors.toSet()));

        Set<Long> roleIds = roleList.stream().mapToLong(e->e.getId()).boxed().collect(Collectors.toSet());
        List<TSysPermission> associatedPermissionByRoleIds = itSysPermissionService.getsAssociatedPermissionByRoleIds(roleIds);
        if(CollectionUtil.isEmpty(associatedPermissionByRoleIds)) {
            String message = String.format("用户[%s]所属角色未配置任何权限", userId);
            throw new BaseException(ErrorCode.NOT_CONFIGURED, message);
        }
        log.debug("用户[{}]配置的权限: {}", userId, associatedPermissionByRoleIds.stream().map(TSysPermission::getName).collect(Collectors.toSet()));
        List<SysPermissionVO> sysPermissionList = associatedPermissionByRoleIds.stream().map(e->{
            SysPermissionVO vo = new SysPermissionVO();
            BeanUtils.copyProperties(e, vo);
            return vo;
        }).collect(Collectors.toList());
        return sysPermissionList;
    }

    private TSysUser buildRandomUser(){
        TSysUser tSysUser = TSysUser.builder()
                .username(randomUsername())
                .password("123456")
                .mobile(randomMobile())
                .mobilePrefix("86")
                .sex(SexEnum.getByValue(randomSex()))
                .email(randomEmail())
                .birthday(randomBirthday())
                .source(1)
                .build();
        return tSysUser;
    }

    // 8~20位,大小写字母,数字,特殊字符(~!@#$%^&-), 非数字开头
    private String randomUsername(){
        return "匿名用户-"+ RandomValueUtils.getStr(10, 11);
    }

    private String randomEmail(){
        return RandomValueUtils.getEmail(5, 12);
    }

    private String randomMobile(){
        return RandomValueUtils.getTel();
    }

    private int randomSex(){
        return RandomValueUtils.getInt(0,3);
    }

    private Date randomBirthday(){
        return RandomValueUtils.getDate("1970-01-01 00:00:00", "2004-01-01 00:00:00");
    }
}
